package webview

import (
	"gitee.com/snxamdf/wui/logs"
)

type WinExtInvokeSyncHandler struct {
}

//组件数据更新监听
func (m WinExtInvokeSyncHandler) BindWidgetUpdateListen(wd RPCData) {
	if component, ok := componentListen[wd.ComponentName]; ok {
		widget := component.GetWidget(wd.WidgetId)
		if widget != nil {
			value := wd.Value
			widget.GetValue().PutValue(value)
			fn := widget.GetEvent()
			if fn != nil {
				r := fn(widget)
				if r != nil && CheckType(r.Type) {
					js, _ := r.Script()
					if js == "" {
						return
					}
					if err := widget.Eval(js); err != nil {
						logs.Error("BindWidgetUpdateListen Callback Function Error:", err)
					} else {
						logs.Debug("BindWidgetUpdateListen Callback Function Success:", r)
					}
				}
				logs.Debug("CBEvent-FN-Result:", r)
			}
		}
	}
}

func (m WinExtInvokeSyncHandler) BindWidgetClickEventListen(wd RPCData, fn Callback) {

}

func (m WinExtInvokeSyncHandler) BindWidgetChangeEventListen(wd RPCData, fn Callback) {

}

//window.external.invoke 监听
func (m WinExtInvokeSyncHandler) Listen(wd RPCData) {
	componentLock.Lock()
	defer componentLock.Unlock()
	//{"type":"update","componentName":"foo","widgetId":"counter","value":1}
	//typed := wd.GetString("type")
	if wd.Type == Update {
		m.BindWidgetUpdateListen(wd)
	} else if wd.Type == Init {
		m.widgetAllInitSyncJS()
	}
}

//所有控件初始化到GoBind.bind
func (m WinExtInvokeSyncHandler) widgetAllInitSyncJS() {
	logs.Debug("所有控件初始化到GoBind.bind")
	b := binding{}
	for _, component := range componentListen {
		b.BindingJS(component.GetWidgets())
		b.EvalJS(component.GetWV())
	}
}
